﻿using PLCS.App.Shared.Service;
using PLCS.Application.Contracts.EquipmentApp.Dtos;

using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Client.IService.ConfigManager;
using PLCS.Client.IService.LogManager;
using PLCS.Domain;
using PLCS.Shared.Common.Constant;

using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace PLCS.App.EquipmentManager.ViewModels.Equipment;

public class EquipmentDetailViewModel : HostDialogViewModel
{
    public EquipmentDetailViewModel(IObjectMapper<EquipmentManagerModule> objectMapper, IEquipmentService equipmentService, IConfigService configService, IOperationLogService logShowService, CacheSettingService cacheSettingService)
    {
        _objectMapper = objectMapper;
        _equipmentService = equipmentService;
        _configService = configService;
        _logShowService = logShowService;
        _cacheSettingService = cacheSettingService;
        View = "设备管理弹窗";
    }

    private EquipmentDto _model;
    private readonly IObjectMapper<EquipmentManagerModule> _objectMapper;
    private readonly IEquipmentService _equipmentService;
    private readonly IConfigService _configService;
    private readonly IOperationLogService _logShowService;
    private readonly CacheSettingService _cacheSettingService;

    public EquipmentDto Model
    {
        get { return _model; }
        set { _model = value; }
    }

    protected override async void Save()
    {
        try
        {
            SavebuttonIsEnabled = false;
            Model.AreaNo = await _configService.GetConfigByNameAsync("AreaNo");
            var equipment = _objectMapper.Map<EquipmentDto, EquipmentEditDto>(Model);
            equipment.AreaNo = _cacheSettingService.cacheSetting.AreaNo;
            equipment.SiteNo = _cacheSettingService.cacheSetting.SiteNo;
            equipment.PdLineNo = _cacheSettingService.cacheSetting.PdLineNo;
            if (equipment.Id != Guid.Empty)
            {
                await _equipmentService.UpdateAsync(equipment);
                Log("修改", equipment);
            }
            else
            {
                await _equipmentService.CreateAsync(equipment);
                Log("新增", equipment);
            }

            ShowMessage("操作成功");
            base.Save();
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
        finally { SavebuttonIsEnabled = true; }
    }

    public override void OnDialogOpened(IDialogParameters parameters)
    {
        if (parameters.ContainsKey("Value"))
        {
            Model = parameters.GetValue<EquipmentDto>("Value");
            Title = "编辑";
        }
        else
        {
            Title = "新增";
            Model = new EquipmentDto();
        }
    }
}